package com.mgs.product.tagger.handlers
{
	import com.mgs.fwk.context.ApplicationContext;
	import com.mgs.fwk.handlers.ActionHandler;
	import com.mgs.product.tagger.controller.ContextController;
	import com.mgs.product.tagger.actions.ApplicationAction;
	import com.mgs.product.tagger.actions.DocumentCreationAction;
	import com.mgs.product.tagger.actions.SaveCellDescriptionAction;
	import com.mgs.product.tagger.dao.DocumentDao;
	import com.mgs.product.tagger.dao.DocumentDaoImpl;
	import com.mgs.product.tagger.model.Document;
	import com.mgs.product.tagger.ui.dto.DtoFactory;
	import com.mgs.product.tagger.ui.dto.NavigationContext;
	
	public class SaveCellDescriptionHandler implements ActionHandler
	{
		private var documentDao:DocumentDao = new DocumentDaoImpl();
		
		public function SaveCellDescriptionHandler()
		{
		}
		
		public function execute(context:ApplicationContext, action:ApplicationAction):void
		{
			if((context as NavigationContext).cell != null)
			{
				if((context as NavigationContext).cell.descriptionDocument == null ||
					(context as NavigationContext).cell.descriptionDocument.file == null)
				{
					var actionCreation:DocumentCreationAction = new DocumentCreationAction();
					actionCreation.document = DtoFactory.createDefaultDocument();
					actionCreation.document.document.name = "desc.txt";
					actionCreation.document.document.content = (context as NavigationContext).cell.description;
					ContextController.instance.processAction(context, actionCreation);
					// update context (necessary)
					(context as NavigationContext).cell = DtoFactory.createCell(actionCreation.document.document);
				}
				documentDao.writeDocumentContent(
					(context as NavigationContext).cell.descriptionDocument,
					(context as NavigationContext).cell.description);
			}
		}
	}
}